package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dataSource.DBContextHolder;
import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.util.CoreLogic;
import com.stlm2.util.Convert;
import com.stlm2.util.StringUtils;
import com.stlm2.util.codecontent.CodeContent;
import net.sf.json.JSONArray;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("seckillGoodsService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class SeckillGoodsService extends BaseServiceImpl<SeckillGoods> {

	@Resource
	private SeckillGoodsDao seckillGoodsDao;
	@Resource
	private UserDao userDao;
	@Resource
	private DdmGoodsDao ddmGoodsDao;
	@Resource
	private GoodSpecificationDao goodSpecificationDao;
	@Resource
	private CommentsDao commentsDao;
	@Resource
	private GoodsOrderDao goodsOrderDao;
	@Resource
	private PurchaseOrderDao purchaseOrderDao;
	@Resource
	private ShopOrderDao shopOrderDao;
	@Resource
	private ActivityService activityService;
	@Resource
	private CoreLogic coreLogic;

	@Override
	protected BaseDao <SeckillGoods> getDao() {
		return seckillGoodsDao;
	}

	/**
	 * 添加秒杀商品
	 * ffl
	 * 2017-12-22 10:43:42
	 * @param token
	 * @param goodsId
	 * @param goodsSpecificationId
	 * @param seckillPrice
	 * @param seckillDate
	 * @param inventory
	 * @return
	 */
	public String addSeckillGoods(String token,String goodsId,String goodsSpecificationId,String seckillPrice,String seckillDate,String inventory){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(StringUtils.isNullOrEmpty(seckillDate)){
			return CodeContent.getModelByCode(0,"未填写秒杀日期",null);
		}
		if (!NumberUtils.isDigits(goodsId)){
			return CodeContent.getModelByCode(0,"未传入合法的商品id",null);
		}
		if (!NumberUtils.isDigits(goodsSpecificationId)){
			return CodeContent.getModelByCode(0,"未传入合法的规格商品id",null);
		}
		if (!NumberUtils.isNumber(seckillPrice)){
			return CodeContent.getModelByCode(0,"未传入合法的秒杀价格",null);
		}
		if(new BigDecimal(seckillPrice).compareTo(new BigDecimal(0))==-1){
			return CodeContent.getModelByCode(0,"秒杀价格必须大于0",null);
		}
		if (!NumberUtils.isDigits(inventory)){
			return CodeContent.getModelByCode(0,"未传入合法秒杀库存",null);
		}
		if(NumberUtils.toInt(inventory)<0){
			return CodeContent.getModelByCode(0,"秒杀库存不能小于0",null);
		}
		String k=" 00:00:00";
		String k2 = seckillDate+k;
		Date startTime=null;
		String t=" 23:59:59";
		String t2 = seckillDate+t;
		Date endTime=null;
		try {
			startTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(k2);
			endTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);

		} catch (Exception e) {
			System.out.println("无法解析时间k2" + t2);
		}
		Calendar cal=Calendar.getInstance();
		try {
			cal.setTime( endTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);
        SeckillGoods param=new SeckillGoods();
        param.setGoodsId(NumberUtils.toInt(goodsId));
        param.setGoodsSpecificationId(NumberUtils.toInt(goodsSpecificationId));
        param.setYear(year);
        param.setMonth(month);
        param.setDay(day);
		List<SeckillGoods> goodsList=seckillGoodsDao.queryList(-1,-1,param);
		if(goodsList!=null&&goodsList.size()>0){
			return CodeContent.getModelByCode(0,"该秒杀商品已经添加了，请不要重复添加！",null);
		}
		ModelMap model=new ModelMap();
		SeckillGoods seckillGoods=new SeckillGoods();
		seckillGoods.setGoodsId(NumberUtils.toInt(goodsId));
		seckillGoods.setGoodsSpecificationId(NumberUtils.toInt(goodsSpecificationId));
		seckillGoods.setYear(year);
		seckillGoods.setMonth(month);
		seckillGoods.setDay(day);
		seckillGoods.setSeckillPrice(new BigDecimal(seckillPrice));
		seckillGoods.setInventory(NumberUtils.toInt(inventory));
		seckillGoods.setSaleVolume(0);
		seckillGoods.setState(true);
		seckillGoods.setStartTime(startTime);
		seckillGoods.setEndTime(endTime);
		seckillGoods.setCreateTime(new Date());
		seckillGoods.setCreateUserId(user.getId());
		seckillGoodsDao.add(seckillGoods);
		return CodeContent.getModelByCode(1,"",model);
	}


	/**
	 * 查询list
	 * ffl
	 * 2017-12-22 11:55:29
	 * @param token
	 * @param goodsId
	 * @param goodsSpecificationId
	 * @param seckillDate
	 * @param state
	 * @param pageNu
	 * @return
	 */
	public String search(String token, String goodsId,String goodsSpecificationId,String seckillDate,String goodsName,String abbreviation,String state,String pageNu,String pageSize){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		int pageNo=1;
		int size=20;
		if(!NumberUtils.isDigits(pageNu)){
			return CodeContent.getModelByCode(0,"未传入查询页数",null);
		}
		pageNo=NumberUtils.toInt(pageNu);
		if(NumberUtils.isDigits(pageSize)){
			size=NumberUtils.toInt(pageSize);
		}
        SeckillGoods param=new SeckillGoods();
		if(NumberUtils.isDigits(goodsId)){
			param.setGoodsId(NumberUtils.toInt(goodsId));
		}
		if(NumberUtils.isDigits(goodsSpecificationId)){
			param.setGoodsSpecificationId(NumberUtils.toInt(goodsSpecificationId));
		}
		if(!StringUtils.isNullOrEmpty(seckillDate)){
			String t=" 23:59:59";
			String t2 = seckillDate+t;
			Date endTime=null;
			try {
				endTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);

			} catch (Exception e) {
				System.out.println("无法解析时间k2" + t2);
			}
			Calendar cal=Calendar.getInstance();
			try {
				cal.setTime( endTime);
				int year = cal.get(Calendar.YEAR);
				int month = cal.get(Calendar.MONTH) + 1;
				int day = cal.get(Calendar.DAY_OF_MONTH);
				param.setYear(year);
				param.setMonth(month);
				param.setDay(day);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(NumberUtils.isDigits(state)){
			if(NumberUtils.toInt(state)==1){
				param.setState(true);
			}
			if(NumberUtils.toInt(state)==0){
				param.setState(false);
			}
		}
		if (StringUtils.isNotNullAndEmpty(goodsName)){
			param.setGoodsName(goodsName);
		}
		if (StringUtils.isNotNullAndEmpty(abbreviation)){
			param.setAbbreviation(abbreviation);
		}
		ModelMap model=new ModelMap();
		PageView pageview=seckillGoodsDao.queryPageView(pageNo, size,param);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertCrmList(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return  new JSONObject(model).toString();


	}

	public List<ModelMap> convertCrmList(List<SeckillGoods> goodsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (goodsList != null &&goodsList.size() > 0) {
			for (SeckillGoods seckillGoods : goodsList) {
				ModelMap map = buildModelCrmList(seckillGoods);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCrmList(SeckillGoods seckillGoods) {
		ModelMap model = new ModelMap();
		model.put("id", seckillGoods.getId());
		model.put("state",seckillGoods.getState()?"有效":"无效");
		model.put("stateValue",seckillGoods.getState()?1:0);
		model.put("seckillDate",seckillGoods.getYear()+"-"+seckillGoods.getMonth()+"-"+seckillGoods.getDay());
		model.put("seckillPrice",seckillGoods.getSeckillPrice());
		model.put("inventory",seckillGoods.getInventory());
		model.put("saleVolume",seckillGoods.getSaleVolume());
		model.put("totalInventory",seckillGoods.getInventory()+seckillGoods.getSaleVolume());
//		model.put("createTime", seckillGoods.getCreateTime() != null ? Convert.toFullYMDHMS(seckillGoods.getCreateTime()) : "");
//		User user=userDao.getById(seckillGoods.getCreateUserId());
//		String userName="";
//		if(user!=null){
//			userName=user.getRealName();
//		}
//		model.put("userName",userName);
		String goodsName="";
		String specificationName="";
		BigDecimal salePrice=new BigDecimal(0);
		DdmGoods goods=ddmGoodsDao.getById(seckillGoods.getGoodsId());
		if(goods!=null){
			goodsName=goods.getName();
			salePrice=goods.getMemberPrice();
		}
		if(seckillGoods.getGoodsSpecificationId()!=null){
			GoodSpecification specification=goodSpecificationDao.getById(seckillGoods.getGoodsSpecificationId());
			if(specification!=null){
				specificationName=specification.getPropertiesName();
				salePrice=specification.getMemberPrice();
			}
		}
        model.put("goodsName",goodsName);
		model.put("specificationName",specificationName);
		model.put("salePrice",salePrice);
		return  model;
	}



	public ModelMap buildModelCrmDetail(SeckillGoods seckillGoods) {
		ModelMap model = new ModelMap();
		model.put("id", seckillGoods.getId());
		model.put("state",seckillGoods.getState()?"有效":"无效");
		model.put("stateValue",seckillGoods.getState()?1:0);
		model.put("seckillDate",seckillGoods.getYear()+"-"+seckillGoods.getMonth()+"-"+seckillGoods.getDay());
		model.put("seckillPrice",seckillGoods.getSeckillPrice());
		model.put("inventory",seckillGoods.getInventory());
		model.put("saleVolume",seckillGoods.getSaleVolume());
		model.put("totalInventory",seckillGoods.getInventory()+seckillGoods.getSaleVolume());
		model.put("createTime", seckillGoods.getCreateTime() != null ? Convert.toFullYMDHMS(seckillGoods.getCreateTime()) : "");
		User user=userDao.getById(seckillGoods.getCreateUserId());
		String userName="";
		if(user!=null){
			userName=user.getRealName();
		}
		model.put("userName",userName);
		String goodsName="";
		String specificationName="";
		BigDecimal salePrice=new BigDecimal(0);
		String mainImg="";
		DdmGoods goods=ddmGoodsDao.getById(seckillGoods.getGoodsId());
		if(goods!=null){
			goodsName=goods.getName();
			salePrice=goods.getMemberPrice();
			mainImg=goods.getMainImg().split(",")[0];
		}
		if(seckillGoods.getGoodsSpecificationId()!=null){
			GoodSpecification specification=goodSpecificationDao.getById(seckillGoods.getGoodsSpecificationId());
			if(specification!=null){
				specificationName=specification.getPropertiesName();
				salePrice=specification.getMemberPrice();
				mainImg=specification.getImage();
			}
		}
		model.put("goodsName",goodsName);
		model.put("specificationName",specificationName);
		model.put("salePrice",salePrice);
		model.put("mainImg",mainImg);
		return  model;
	}


	/**
	 * 获取秒杀商品详情
	 * ffl
	 * 2017-12-22 11:59:32
	 * @param token
	 * @param id
	 * @return
	 */
	public String  getDetails(String token,String id ){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入合法的秒杀商品id",null);
		}
		SeckillGoods seckillGoods=seckillGoodsDao.getById(NumberUtils.toInt(id));
		return CodeContent.getModelByCode(1,"",buildModelCrmDetail(seckillGoods));
	}


	/**
	 * 编辑 秒杀商品 价格和库存
	 * ffl
	 * 2017-12-22 13:59:21
	 * @param token
	 * @param id
	 * @param seckillPrice
	 * @param inventory
	 * @return
	 */
	public String editSeckillGoods(String token ,String id ,String seckillPrice,String inventory){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入合法的秒杀商品id",null);
		}
		if (!NumberUtils.isNumber(seckillPrice)){
			return CodeContent.getModelByCode(0,"未传入合法的秒杀价格",null);
		}
		if(new BigDecimal(seckillPrice).compareTo(new BigDecimal(0))==-1){
			return CodeContent.getModelByCode(0,"秒杀价格必须大于0",null);
		}
		if (!NumberUtils.isDigits(inventory)){
			return CodeContent.getModelByCode(0,"未传入合法秒杀库存",null);
		}
		if(NumberUtils.toInt(inventory)<0){
			return CodeContent.getModelByCode(0,"秒杀库存不能小于0",null);
		}
		SeckillGoods seckillGoods=seckillGoodsDao.getById(NumberUtils.toInt(id));
		if(seckillGoods==null){
			return CodeContent.getModelByCode(0,"未找到id为"+id+"的秒杀商品",null);
		}
		seckillGoods.setSeckillPrice(new BigDecimal(seckillPrice));
		seckillGoods.setInventory(NumberUtils.toInt(inventory));
		seckillGoodsDao.modify(seckillGoods);
		return CodeContent.getModelByCode(1,"",null);
	}


	/**
	 * 上下架秒杀商品
	 *ffl
	 * 2017-12-22 14:08:24
	 * @param token
	 * @param state
	 * @return
	 */
	public  String editState(String token ,Boolean state,String id){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if (!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入合法的秒杀商品id",null);
		}
		SeckillGoods seckillGoods=seckillGoodsDao.getById(NumberUtils.toInt(id));
		if(seckillGoods==null){
			return CodeContent.getModelByCode(0,"未找到id为"+id+"的秒杀商品",null);
		}
		seckillGoods.setState(state);
		seckillGoodsDao.modify(seckillGoods);
		return CodeContent.getModelByCode(1,"",null);
	}


	/**
	 * ======================================      前台接口              ===============================================================================
	 */

	/**
	 *  前台 首页  是否开启秒杀 及展示秒杀商品
	 * ffl
	 * 2017-12-22 17:08:09
	 * @return
	 */
	public String indexList( String companyCode){
		int pageNo=1;
		ModelMap model=new ModelMap();
		Date current = new Date();
		Calendar cal=Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);

		String t=" 23:59:59";
		String t2 = Convert.toShortYMD(current)+t;
		Date timeEnd=null;
		try {
			timeEnd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);
		} catch (Exception e) {
			System.out.println("无法解析时间k2" + t2);
		}
		SeckillGoods param=new SeckillGoods();
		param.setYear(year);
		param.setMonth(month);
		param.setDay(day);
		param.setGoodsState(true);
		PageView pageview=seckillGoodsDao.queryPageView(pageNo,2,param);
		model.put("code",1);
		model.put("msg","success");
		model.put("timeNow",current.getTime());
		model.put("endTime",timeEnd.getTime());
		model.put("seckillState",activityService.SeckillActivityState(companyCode));
		if (pageview != null){
			model.put("datas",convert(pageview.getRecords()));
		}
		return  new JSONObject(model).toString();

	}

	/**
	 *  前台 查询 秒杀 时间场次
	 * ffl
	 * 2017-12-22 17:08:09
	 * @param sort
	 * @return
	 */
	public String timeSession( String companyCode,String sort){
		int num=0;
		if(NumberUtils.isNumber(sort)){
			num=NumberUtils.toInt(sort);
		}
		ModelMap model=new ModelMap();
		Date current = new Date();
		Date endTime=null;
		if(num==0){
			endTime=current;
		}
		if (num>0){

			endTime = Convert.afterDay(current,num);
		}
		if(num<0){
			endTime=Convert.beforeDay(current,num*-1);
		}
		Calendar cal=Calendar.getInstance();
		try {
			cal.setTime( endTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String t=" 23:59:59";
		String t2 = Convert.toShortYMD(current)+t;
		Date timeEnd=null;
		try {
			timeEnd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);
		} catch (Exception e) {
			System.out.println("无法解析时间k2" + t2);
		}

		model.put("code",1);
		model.put("msg","success");
		model.put("timeNow",current.getTime());
		model.put("endTime",timeEnd.getTime());
		model.put("weekNow",Convert.getWeekOfDate(current));
		model.put("weekThen",Convert.getWeekOfDate(endTime));
		model.put("weekNow2",Convert.WeekOfDate(current));
		model.put("weekThen2",Convert.WeekOfDate(endTime));
		model.put("sort",sort);
		model.put("seckillState",activityService.SeckillActivityState(companyCode));

		return  new JSONObject(model).toString();

	}

	/**
	 *  前台 查询 秒杀商品
	 * ffl
	 * 2017-12-22 17:08:09
	 * @param sort
	 * @param pageNu
	 * @return
	 */
	public String list( String companyCode,String sort,String pageNu){
		int num=0,pageNo=1;
		if(NumberUtils.isNumber(sort)){
			num=NumberUtils.toInt(sort);
		}
        if(!NumberUtils.isDigits(pageNu)){
			return CodeContent.getModelByCode(0,"未传入查询页数",null);
		}
		pageNo=NumberUtils.toInt(pageNu);
		ModelMap model=new ModelMap();
		Date current = new Date();
		Date endTime=null;
        if(num==0){
			endTime=current;
		}
		if (num>0){

			endTime = Convert.afterDay(current,num);
		}
		if(num<0){
			endTime=Convert.beforeDay(current,num*-1);
		}
		Calendar cal=Calendar.getInstance();
		try {
			cal.setTime( endTime);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);

		String t=" 23:59:59";
		String t2 = Convert.toShortYMD(current)+t;
		Date timeEnd=null;
		try {

			timeEnd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);

		} catch (Exception e) {
			System.out.println("无法解析时间k2" + t2);
		}
		SeckillGoods param=new SeckillGoods();
		param.setYear(year);
		param.setMonth(month);
		param.setDay(day);
		param.setGoodsState(true);

        PageView pageview=seckillGoodsDao.queryPageView(pageNo,20,param);
		model.put("code",1);
		model.put("msg","success");
		model.put("timeNow",current.getTime());
		model.put("endTime",timeEnd.getTime());
		model.put("weekNow",Convert.getWeekOfDate(current));
		model.put("weekThen",Convert.getWeekOfDate(endTime));
		model.put("weekNow2",Convert.WeekOfDate(current));
		model.put("weekThen2",Convert.WeekOfDate(endTime));
		model.put("sort",sort);

		model.put("seckillState",activityService.SeckillActivityState(companyCode));
		if (pageview != null){
			model.put("datas",convert(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}

		return  new JSONObject(model).toString();

	}

	public List<ModelMap> convert(List<SeckillGoods> goodsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (goodsList != null &&goodsList.size() > 0) {
			for (SeckillGoods seckillGoods : goodsList) {
				ModelMap map = buildModel(seckillGoods);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModel(SeckillGoods seckillGoods) {
		ModelMap model = new ModelMap();
		model.put("id", seckillGoods.getId());
		model.put("state",seckillGoods.getState()?"有效":"无效");
		model.put("stateValue",seckillGoods.getState()?1:0);
		model.put("seckillDate",seckillGoods.getYear()+"-"+seckillGoods.getMonth()+"-"+seckillGoods.getDay());
		model.put("seckillPrice",seckillGoods.getSeckillPrice());
		model.put("inventory",seckillGoods.getInventory());

		Date current = new Date();
		String t=" 23:59:59";
		String t2 = Convert.toShortYMD(current)+t;
		Date timeEnd=null;
		try {

			timeEnd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);

		} catch (Exception e) {
			System.out.println("无法解析时间k2" + t2);
		}


		int totalInventory=seckillGoods.getInventory()+seckillGoods.getSaleVolume();
		int saleVolume=seckillGoods.getSaleVolume()*100;
		BigDecimal  percent=new BigDecimal(saleVolume).divide(new BigDecimal(totalInventory));
		model.put("percent",percent.setScale(2,BigDecimal.ROUND_DOWN));
		if(timeEnd.getTime()-seckillGoods.getEndTime().getTime()>0){
			model.put("percent",100);
		}
		String goodsName="";
		String specificationName="";
		BigDecimal salePrice=new BigDecimal(0);
		String mainImg="";
		DdmGoods goods=ddmGoodsDao.getById(seckillGoods.getGoodsId());
		if(goods!=null){
			goodsName=goods.getName();
			salePrice=goods.getMemberPrice();
			mainImg=goods.getMainImg().split(",")[0];
		}
		if(seckillGoods.getGoodsSpecificationId()!=null){
			GoodSpecification specification=goodSpecificationDao.getById(seckillGoods.getGoodsSpecificationId());
			if(specification!=null){
				specificationName=specification.getPropertiesName();
				salePrice=specification.getMemberPrice();
				mainImg=specification.getImage();
			}
		}
		model.put("goodsName",goodsName);
		model.put("specificationName",specificationName);
		model.put("salePrice",salePrice);
		model.put("mainImg",mainImg);
		return  model;
	}

	/**
	 *  秒杀商品详情
	 * ffl
	 * 2017-12-26 11:19:21
	 * @param id
	 * @return
	 */
	public String seckillGoodsDetail(String companyCode,String id){
		if (!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0,"未传入合法的秒杀商品id",null);
		}
		SeckillGoods seckillGoods=seckillGoodsDao.getById(NumberUtils.toInt(id));
		if(seckillGoods==null){
			return CodeContent.getModelByCode(0,"未找到id为"+id+"的秒杀商品",null);
		}


		return CodeContent.getModelByCode(1,"",buildModelDetail(seckillGoods,companyCode));
	}

	public ModelMap buildModelDetail(SeckillGoods seckillGoods,String companyCode) {
		ModelMap model = new ModelMap();
		model.put("id", seckillGoods.getId());
		model.put("goodsId",seckillGoods.getGoodsId());
		model.put("goodsSpecificationId",seckillGoods.getGoodsSpecificationId()!=null?seckillGoods.getGoodsSpecificationId():"");
		model.put("state",seckillGoods.getState()?"有效":"无效");
		model.put("stateValue",seckillGoods.getState()?1:0);
		model.put("seckillDate",seckillGoods.getYear()+"-"+seckillGoods.getMonth()+"-"+seckillGoods.getDay());
		model.put("seckillPrice",seckillGoods.getSeckillPrice());
		model.put("inventory",seckillGoods.getInventory());
		int totalInventory=seckillGoods.getInventory()+seckillGoods.getSaleVolume();
		int saleVolume=seckillGoods.getSaleVolume()*100;
		BigDecimal  percent=new BigDecimal(saleVolume).divide(new BigDecimal(totalInventory));
		model.put("percent",percent.setScale(2,BigDecimal.ROUND_DOWN));
		String goodsName="";
		String specificationName="";
		BigDecimal salePrice=new BigDecimal(0);
		String mainImg="";
		String detailsImg="";
		String goodsExplain="";
		String safeguard="";
		String parameter="";
		DdmGoods ddmGoods=ddmGoodsDao.getById(seckillGoods.getGoodsId());
		if(ddmGoods!=null){
			goodsName=ddmGoods.getName();
			salePrice=ddmGoods.getMemberPrice();
			mainImg=ddmGoods.getMainImg().split(",")[0];
			detailsImg=ddmGoods.getDetailsImg();
			goodsExplain=ddmGoods.getGoodsExplain();
			safeguard=ddmGoods.getSafeguard();
			parameter=ddmGoods.getParameter();
			if(seckillGoods.getGoodsSpecificationId()!=null){
				GoodSpecification specification=goodSpecificationDao.getById(seckillGoods.getGoodsSpecificationId());
				if(specification!=null){
					specificationName=specification.getPropertiesName();
					salePrice=specification.getMemberPrice();
					mainImg=specification.getImage();
					parameter=specification.getParameter()!=null?specification.getParameter():ddmGoods.getParameter();
				}
			}
		}
		//评论
		Comments comments=new Comments();
		comments.setIsValid(true);
		comments.setGoodsId(ddmGoods.getId());
		PageView pageView=commentsDao.queryPageView(-1,3,comments);
		List<Comments> commentsList=pageView.getRecords();
		model.put("commentsList",convertCommentsList(commentsList));
		model.put("commentsCount",pageView.getRowCount());
		model.put("goodsName",goodsName);
		model.put("specificationName",specificationName);
		model.put("salePrice",salePrice);
		model.put("mainImg",mainImg);
		model.put("detailsImg",detailsImg);
		model.put("goodsExplain",goodsExplain);
		model.put("safeguard",safeguard);
		model.put("parameter",parameter);
		model.put("seckillState",activityService.SeckillActivityState(companyCode));
		Date current = new Date();
		String t=" 23:59:59";
		String t2 = Convert.toShortYMD(current)+t;
		Date timeEnd=null;
		try {

			timeEnd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);

		} catch (Exception e) {
			System.out.println("无法解析时间k2" + t2);
		}
		int rounds=0;
	    if(timeEnd.getTime()-seckillGoods.getEndTime().getTime()>0){
           rounds=-1;
		}else if(timeEnd.getTime()-seckillGoods.getEndTime().getTime()==0){
	    	rounds=0;
		}else if (timeEnd.getTime()-seckillGoods.getEndTime().getTime()<0){
			rounds=1;
		}

		model.put("rounds",rounds);
		model.put("timeNow",current.getTime());
		model.put("endTime",seckillGoods.getEndTime().getTime());
		return  model;
	}


	public List<ModelMap> convertCommentsList(List<Comments> commentsList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (commentsList != null && commentsList.size() > 0) {
			for (Comments comments : commentsList) {
				ModelMap map = buildModelCommentsList(comments);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelCommentsList(Comments comments) {
		ModelMap model = new ModelMap();
		User user=userDao.getById(comments.getUserId());
		String userName=user.getRealName();
		if(NumberUtils.isDigits(userName)){
			userName=userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
		}
		model.put("id",comments.getId());
		model.put("userName",userName);
		model.put("avotorr",user.getAvotorr());
		model.put("gradedValue",comments.getGradedValue());
		model.put("content",comments.getContent()!=null? comments.getContent():"" );
		model.put("imgUrl",comments.getImgUrl()!=null? comments.getImgUrl():"");
		model.put("replyMessage",comments.getReplyMessage()!=null? comments.getReplyMessage():"");
		GoodsOrder goodsOrder=goodsOrderDao.getById(comments.getOrderId());
		if(goodsOrder.getGoodsSpecificationId()!=null){
			GoodSpecification goodSpecification =goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
			model.put("propertiesName",goodSpecification.getPropertiesName());
		}else {
			model.put("propertiesName","");
		}

		return  model;
	}




	public Map<String, Object> confirmOrder( Integer userId,String id) {
		Map<String, Object> map = new HashMap<String, Object>();// 最外层{} 01

		 /*
		 *  商品清单
		 * */
		if (!NumberUtils.isDigits(id)) {
			map.put("code", 0);
			map.put("msg", "秒杀商品id不能为空");
			return map;
		}
		SeckillGoods seckillGoods=seckillGoodsDao.getById(NumberUtils.toInt(id ));
		if(seckillGoods==null){
			map.put("code", 0);
			map.put("msg", "秒杀商品id为"+id+"的商品未找到");
			return map;
		}

		if(!seckillGoods.getState()){
			map.put("code", 0);
			map.put("msg", "秒杀商品id为"+id+"的商品已下架");
			return map;
		}
		Date current=new Date();
		if(current.getTime()>seckillGoods.getEndTime().getTime()){
			map.put("code", 0);
			map.put("msg", "秒杀商品id为"+id+"的商品秒杀已结束");
			return map;
		}
		if(current.getTime()<seckillGoods.getStartTime().getTime()){
			map.put("code", 0);
			map.put("msg", "秒杀商品id为"+id+"的商品秒杀还未开始");
			return map;
		}
		if(seckillGoods.getInventory()<=0){
			map.put("code", 0);
			map.put("msg", "秒杀商品id为"+id+"的商品已秒完");
			return map;
		}
		Map<String, Object> goodMap = new HashMap<String, Object>(); //good所用{} 02
		int goodId=seckillGoods.getGoodsId();
		int gooodSpecificationId = seckillGoods.getGoodsSpecificationId()!=null?seckillGoods.getGoodsSpecificationId():0;
		BigDecimal goodsPrice = new BigDecimal(0);
		String propertiesName = "";
		//处理商品清单
		//从数据库中获取商品对象
		DdmGoods good = ddmGoodsDao.getById(goodId);
		if (good == null) {
			map.put("code", 0);
			map.put("msg", "商品不存在");
			return map;
		}
		if (good.getState() == false) {
			map.put("code", 0);
			map.put("msg", "商品状态无效");
			map.put("msg", "无效商品");
			return map;
		}
		goodMap.put("goodName", good.getName());
		String imgUrl=good.getMainImg().split(",")[0];
		goodsPrice=good.getMemberPrice();
		//获取商品规格组合名称
		if (gooodSpecificationId!=0) {
			GoodSpecification goodSpecification = goodSpecificationDao.getById(gooodSpecificationId);
			if(goodSpecification==null){
				map.put("code",0);
				map.put("msg","商品规格不存在");
				return map;
			}
			if(goodId!=goodSpecification.getGoodId()){
				map.put("code",0);
				map.put("msg","商品和商品规格对象不一致");
				return  map ;

			}
			imgUrl=goodSpecification.getImage();
			propertiesName = goodSpecification.getPropertiesName();
			goodsPrice = goodSpecification.getMemberPrice();
		}
		goodMap.put("propertiesName", propertiesName);
		goodMap.put("imgUrl", imgUrl);
		BigDecimal saveMoney =goodsPrice.subtract(seckillGoods.getSeckillPrice());
		goodMap.put("goodsPrice",seckillGoods.getSeckillPrice());
		goodMap.put("num", 1);
		map.put("goods", goodMap);
		if(saveMoney.compareTo(new BigDecimal(0))==1){
			map.put("saveMoney",saveMoney);
		}else {
			map.put("saveMoney",new BigDecimal(0));
		}
		map.put("totalMoney",seckillGoods.getSeckillPrice());
		map.put("code", 1);
		map.put("msg", "success");
		return map;
	}

	/**
	 *  我的秒杀订单
	 * ffl
	 * 2017-12-28 09:24:52
	 * @param token
	 * @param pageNu
	 * @return
	 */
	public String seckillOrder(String token,String pageNu){
		User user=userDao.getByToken(token);
		if (user==null){
			return CodeContent.getModelByCode(-1,"",null);
		}
		if(!NumberUtils.isDigits(pageNu)){
			return CodeContent.getModelByCode(0,"未传入查询页数",null);
		}
		int pageNo=NumberUtils.toInt(pageNu);
		GoodsOrder param=new GoodsOrder();
		param.setUserId(user.getId());
		param.setSeckill(true);
		PageView pageview=goodsOrderDao.queryPageView(pageNo,20,param);
		ModelMap model=new ModelMap();
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertOrder(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}
		return  new JSONObject(model).toString();
	}


	public List<ModelMap> convertOrder(List<GoodsOrder> goodsOrderList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (goodsOrderList != null &&goodsOrderList.size() > 0) {
			for (GoodsOrder goodsOrder : goodsOrderList) {
				ModelMap map = buildModelOrder(goodsOrder);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelOrder(GoodsOrder goodsOrder) {
		ModelMap model = new ModelMap();
		model.put("id", goodsOrder.getId());
		model.put("orderState",goodsOrder.getOrderState()!=null?goodsOrder.getOrderState().toString():"");
		model.put("orderStateValue",goodsOrder.getOrderStateValue());
		model.put("purchaseOrderCode",goodsOrder.getPurchaseOrderCode());
		model.put("seckillPrice",goodsOrder.getSalePrice());
		model.put("shopOrderCode",goodsOrder.getShopOrderCode());
		String goodsName="";
		String specificationName="";
		String mainImg="";
		DdmGoods goods=ddmGoodsDao.getById(goodsOrder.getGoodsId());
		if(goods!=null){
			goodsName=goods.getName();
			mainImg=goods.getMainImg().split(",")[0];
		}
		if(goodsOrder.getGoodsSpecificationId()!=null){
			GoodSpecification specification=goodSpecificationDao.getById(goodsOrder.getGoodsSpecificationId());
			if(specification!=null){
				specificationName=specification.getPropertiesName();
				mainImg=specification.getImage();
			}
		}
		model.put("goodsName",goodsName);
		model.put("specificationName",specificationName);
		model.put("mainImg",mainImg);
		model.put("createTime",Convert.toFullYMDHMS(goodsOrder.getCreateTime()));
		return  model;
	}


	public Boolean updateInventory(Integer id,FlowType flowType){
       SeckillGoods seckillGoods=seckillGoodsDao.getById(id);
		synchronized (seckillGoods) {
			//处理秒杀库存
			if (FlowType.Add.equals(flowType)) {
				if (seckillGoods.getSaleVolume()-1 <0)
					return false;

				seckillGoods.setSaleVolume(seckillGoods.getSaleVolume()-1);
				seckillGoods.setInventory(seckillGoods.getInventory() + 1);
			}
			else if (FlowType.Reduce.equals(flowType)) {
				if (seckillGoods.getInventory() <=0)
					return false;

				seckillGoods.setInventory(seckillGoods.getInventory()-1);
				seckillGoods.setSaleVolume(seckillGoods.getSaleVolume()+1);
			}

			seckillGoodsDao.modify(seckillGoods);

			return true;
		}

	}


	public void cancelOrder(){
		Date current = new Date();
		Date cancelTime = Convert.beforeMinute(current,10);//十分钟前
		System.out.println("时间:"+Convert.toFullYMDHMS(cancelTime));
		PurchaseOrder param = new PurchaseOrder();
		param.setOrderState(OrderState.Create);
		param.setCreateTime(cancelTime);
		param.setSeckill(true);
		List<PurchaseOrder> purchaseOrderList = purchaseOrderDao.queryList(-1, -1, param);
		if (purchaseOrderList != null && purchaseOrderList.size() > 0) {
			for (PurchaseOrder purchaseOrder : purchaseOrderList) {
				cancelOrder(purchaseOrder,CancelReason.System);
			}
		}

	}
	//取消订单
	public Boolean  cancelOrder(PurchaseOrder purchaseOrder,CancelReason cancelReason){
		if(purchaseOrder == null)
			return false;

		synchronized (purchaseOrder) {
			if (!OrderState.Create.equals(purchaseOrder.getOrderState()))
				return false;
			if(!purchaseOrder.getSeckill())
				return false;


			//修改一级订单状态
			purchaseOrder.setOrderState(OrderState.Cancel);
			purchaseOrder.setCancelTime(new Date());
			purchaseOrder.setCancelReason(cancelReason);
			purchaseOrderDao.modify(purchaseOrder);

			//修改二级订单状态
			ShopOrder shopOrderParam=new ShopOrder();
			shopOrderParam.setPurchaseOrderCode(purchaseOrder.getCode());
			List<ShopOrder> shopOrderList = shopOrderDao.queryList(-1, -1, shopOrderParam);
			if(shopOrderList != null && shopOrderList.size() > 0){
				for (ShopOrder shopOrder:shopOrderList){
					if(!OrderState.Create.equals(shopOrder.getOrderState()))
						continue;

					shopOrder.setOrderState(OrderState.Cancel);
					shopOrder.setCancelTime(purchaseOrder.getCancelTime());
					shopOrder.setCancelReason(cancelReason);
					shopOrderDao.modify(shopOrder);

					//修改三级订单状态
					GoodsOrder goodsOrderParam = new GoodsOrder();
					goodsOrderParam.setShopOrderCode(shopOrder.getCode());
					goodsOrderParam.setOrderState(OrderState.Create);
					List<GoodsOrder> goodsOrderList= goodsOrderDao.queryList(-1, -1, goodsOrderParam);
					if(goodsOrderList != null && goodsOrderList.size() > 0){
						for (GoodsOrder goodsOrder :goodsOrderList) {
							goodsOrder.setOrderState(OrderState.Cancel);
							goodsOrder.setCancelTime(purchaseOrder.getCancelTime());
							goodsOrderDao.modify(goodsOrder);
							if(goodsOrder.getSeckill()){
								coreLogic.updateInventory(goodsOrder.getSeckillGoodsId(),FlowType.Add);
							}
						}
					}
				}
			}

			return true;
		}

	}
	public void  cancelOrderThread(){

		for (DateSourceType dateSourceType: DateSourceType.values()) {
			Thread threadS=  new Thread_v1(dateSourceType);
			threadS.start();
		}

	}
	class  Thread_v1 extends  Thread{
		DateSourceType dateSourceType1;
		Thread_v1(DateSourceType dateSourceType){
			this.dateSourceType1 = dateSourceType;

		}
		public void run() {

			try {
				System.out.println("取消十分钟之前未支付的秒杀订单   公司编号:"+dateSourceType1.getIntValue()+"--执行开始");
				DBContextHolder.setDBType(dateSourceType1.toString());
				cancelOrder();
				DBContextHolder.clearDBType();
				System.out.println("取消十分钟之前未支付的秒杀订单   公司编号:"+dateSourceType1.getIntValue()+"--执行结束");
			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				System.out.println("叮当淘");
			}

		}
	}

}